package FM2_15577.back_end;

import java.sql.*;

public class Connector {
    private Connection conn = null;
    private Statement stmt = null;
    private ResultSet rs = null;
    public void start() throws SQLException {
        try {
            this.conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank?useUnicode=true&characterEncoding=utf8", "bankAdmin", "bank@Java2023");
            this.stmt = conn.createStatement();
        } catch (SQLException ex) {
            throw ex;
        }
    }

    public void execute(String query) throws SQLException {
        try {
            if (this.stmt.execute(query)) {
                this.rs = this.stmt.getResultSet();
            }
        } 
        catch (SQLException ex) {
            throw ex;
        }
    }

    public void melock() throws SQLException {
        try {
            this.stmt.execute("lock tables AccountInfo read");
            this.stmt.execute("lock tables AccountInfo write");
        } catch (SQLException ex) {
            throw ex;
        }
    }

    public void melockadmin() throws SQLException {
        try {
            this.stmt.execute("lock tables AdminInfo read");
            this.stmt.execute("lock tables AdminInfo write");
        } catch (SQLException ex) {
            throw ex;
        }
    }

    public void meunlock() throws SQLException {
        try {
            this.stmt.execute("unlock tables");
        } catch (SQLException ex) {
            throw ex;
        }
    }

    public ResultSet getResultSet() {
        return this.rs;
    }

    public void close() {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) { }
            rs = null;
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) { }
            stmt = null;
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) { }
            conn = null;
        }
    }
}